package org.jeecg.modules.demo.dz.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.dz.entity.DzMaterialSkuCart;
import org.jeecg.modules.demo.dz.service.IDzMaterialSkuCartService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.manage.entity.DzMaterialSku;
import org.jeecg.modules.demo.manage.service.IDzMaterialSkuService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 购物清单
 * @Author: jack
 * @Date:   2024-11-24
 * @Version: V1.0
 */
@Api(tags="购物清单")
@RestController
@RequestMapping("/dz/dzMaterialSkuCart")
@Slf4j
public class DzMaterialSkuCartController extends JeecgController<DzMaterialSkuCart, IDzMaterialSkuCartService> {
	@Autowired
	private IDzMaterialSkuCartService dzMaterialSkuCartService;
	@Autowired
	private IDzMaterialSkuService dzMaterialSkuService;

	/**
	 * 分页列表查询
	 *
	 * @param dzMaterialSkuCart
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "购物清单-分页列表查询")
	@ApiOperation(value="购物清单-分页列表查询", notes="购物清单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<DzMaterialSkuCart>> queryPageList(DzMaterialSkuCart dzMaterialSkuCart,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        QueryWrapper<DzMaterialSkuCart> queryWrapper = QueryGenerator.initQueryWrapper(dzMaterialSkuCart, req.getParameterMap());
		Page<DzMaterialSkuCart> page = new Page<DzMaterialSkuCart>(pageNo, pageSize);
		IPage<DzMaterialSkuCart> pageList = dzMaterialSkuCartService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @ApiOperation(value="购物车-分页列表查询", notes="购物车-分页列表查询")
	 @GetMapping(value = "/pageMyCartList")
	 public Result<IPage<DzMaterialSkuCart>> pageMyCartList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															@RequestParam(name="pageSize", defaultValue="999") Integer pageSize,
															HttpServletRequest req) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 QueryWrapper<DzMaterialSkuCart> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("create_id",sysUser.getId());
		 queryWrapper.eq("is_deleted","0");
		 queryWrapper.orderByDesc("create_time");
		 Page<DzMaterialSkuCart> page = new Page<DzMaterialSkuCart>(pageNo, pageSize);
		 IPage<DzMaterialSkuCart> pageList = dzMaterialSkuCartService.page(page, queryWrapper);
		 List<DzMaterialSkuCart> records = pageList.getRecords();
		 if(CollectionUtil.isNotEmpty(records)){
			 List<String> skuIds = records.stream().map(r -> r.getSkuId()).collect(Collectors.toList());
			 List<DzMaterialSku> dzMaterialSkus = dzMaterialSkuService.listByIds(skuIds);
			 if(CollectionUtil.isNotEmpty(dzMaterialSkus)){
				 Map<String, DzMaterialSku> skuMap = dzMaterialSkus.stream().collect(Collectors.toMap(DzMaterialSku::getId, sku -> sku));
				 for (int i = 0; i < records.size(); i++) {
					 DzMaterialSkuCart dzMaterialSkuCart = records.get(i);
					 if(skuMap.containsKey(dzMaterialSkuCart.getSkuId())){
						 DzMaterialSku dzMaterialSku = skuMap.get(dzMaterialSkuCart.getSkuId());
						 dzMaterialSkuCart.setSpuName(dzMaterialSku.getSpuName());
						 dzMaterialSkuCart.setCategoryFullPath(dzMaterialSku.getCategoryFullPath());
						 dzMaterialSkuCart.setMinPrice(dzMaterialSku.getMinPrice());
						 dzMaterialSkuCart.setMaxPrice(dzMaterialSku.getMaxPrice());
						 dzMaterialSkuCart.setOriginPrice(dzMaterialSku.getOriginPrice());
						 dzMaterialSkuCart.setNowPrice(dzMaterialSku.getNowPrice());
						 dzMaterialSkuCart.setImageUrl(dzMaterialSku.getImage());
						 dzMaterialSkuCart.setSkuNo(dzMaterialSku.getSkuNo());
					 }
				 }
			 }
		 }

		 return Result.OK(pageList);
	 }

	/**
	 *   添加
	 *
	 * @param dzMaterialSkuCart
	 * @return
	 */
	@AutoLog(value = "购物清单-添加")
	@ApiOperation(value="购物清单-添加", notes="购物清单-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody DzMaterialSkuCart dzMaterialSkuCart) {
		String skuId = dzMaterialSkuCart.getSkuId();
		if(StringUtils.isEmpty(skuId)){
			return Result.error("skuId不能为空！");
		}
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		List<DzMaterialSkuCart> list = dzMaterialSkuCartService
				.lambdaQuery()
				.eq(DzMaterialSkuCart::getSkuId, skuId)
				.eq(DzMaterialSkuCart::getCreateId, loginUser.getId())
				.eq(DzMaterialSkuCart::getIsDeleted, 0)
				.list();
		Integer quantity = dzMaterialSkuCart.getQuantity();
		if(quantity == null){
			quantity = 1;
		}
		if(CollectionUtil.isNotEmpty(list)){
			DzMaterialSkuCart sku = list.get(0);
			dzMaterialSkuCartService.lambdaUpdate().setSql(" quantity = quantity + "+quantity).eq(DzMaterialSkuCart::getId,sku.getId()).update();
		}else{
			dzMaterialSkuCart.setQuantity(quantity != null ? quantity : 1);
			dzMaterialSkuCartService.save(dzMaterialSkuCart);
		}

		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param dzMaterialSkuCart
	 * @return
	 */
	@AutoLog(value = "购物清单-编辑")
	@ApiOperation(value="购物清单-编辑", notes="购物清单-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody DzMaterialSkuCart dzMaterialSkuCart) {
		dzMaterialSkuCartService.updateById(dzMaterialSkuCart);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "购物清单-通过id删除")
	@ApiOperation(value="购物清单-通过id删除", notes="购物清单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		this.dzMaterialSkuCartService.lambdaUpdate().set(DzMaterialSkuCart::getIsDeleted,1)
				.eq(DzMaterialSkuCart::getSkuId,id)
				.eq(DzMaterialSkuCart::getCreateId,loginUser.getId())
				.update();
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "购物清单-批量删除")
	@ApiOperation(value="购物清单-批量删除", notes="购物清单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		this.dzMaterialSkuCartService.lambdaUpdate().set(DzMaterialSkuCart::getIsDeleted,1)
				.in(DzMaterialSkuCart::getSkuId,Arrays.asList(ids.split(",")))
				.eq(DzMaterialSkuCart::getCreateId,loginUser.getId())
				.update();
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "购物清单-通过id查询")
	@ApiOperation(value="购物清单-通过id查询", notes="购物清单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<DzMaterialSkuCart> queryById(@RequestParam(name="id",required=true) String id) {
		DzMaterialSkuCart dzMaterialSkuCart = dzMaterialSkuCartService.getById(id);
		if(dzMaterialSkuCart==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(dzMaterialSkuCart);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param dzMaterialSkuCart
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DzMaterialSkuCart dzMaterialSkuCart) {
        return super.exportXls(request, dzMaterialSkuCart, DzMaterialSkuCart.class, "购物清单");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DzMaterialSkuCart.class);
    }

}
